package icu.jiapeng.DemoJava.interfaces;

import lombok.SneakyThrows;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 带有code属性的枚举类型
 */
@Deprecated
public interface WithCodeEnum {
    /**
     * type-values缓存
     */
    Map<Class<?>, Method> METHOD_CACHE = new HashMap<>();
    /**
     * 获取code
     * @return code
     */
    int getCode();
    /**
     * 根据code获取枚举
     * @param code code
     * @return 枚举
     */
    @SuppressWarnings("unchecked")
    @SneakyThrows
    static <E extends Enum<E> & WithCodeEnum> E getEnumByCode(Class<E> type, int code){
        Method values = METHOD_CACHE.get(type);
        if (values == null){
            values = type.getDeclaredMethod("values");
            METHOD_CACHE.put(type, values);
        }
        for (E e : (E[]) values.invoke(null)) {
            if(e.getCode() == code){
                return e;
            }
        }
        return null;
    }
}
